package api

import (
	"TaskAssignmentSystem/internal/app/dao"
	"TaskAssignmentSystem/internal/app/services"
	"TaskAssignmentSystem/internal/pkg/middleware/handler"
	"TaskAssignmentSystem/pkg/oss"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"fmt"
	"github.com/go-the-way/exl"
	"github.com/kataras/iris/v12"
	"io/ioutil"
	"os"
	"time"
)

const (
	ZXZ_PHONE_CODE = "ZXZ_PHONE_CODE"
	ZXZ_PHONE_OPEN = "ZXZ_PHONE_OPEN"
)

func IsOpenHandler(ctx iris.Context) {
	var dictServe services.SystemDictService
	if data, err := dictServe.GetValueByCode(ZXZ_PHONE_OPEN); err != nil {
		ctx.JSON(utils.ResponseData(false))
		return
	} else {
		if data == "ON" {
			ctx.JSON(utils.ResponseData(true))
			return
		} else {
			ctx.JSON(utils.ResponseData(false))
			return
		}
	}
}

type PhoneIsOpenRequest struct {
	Code string `json:"code" validate:"required"` //ON是开，OFF是关
}

func SetIsOpenHandler(ctx iris.Context) {
	var RequestParams PhoneIsOpenRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var systemDictDao dao.Common[dao.SystemDict]
	systemDictDao.Query = map[string]interface{}{"dict_code": ZXZ_PHONE_OPEN}
	if res, err := systemDictDao.First(systemDictDao.Query); err != nil {
		var record dao.SystemDict
		record.DictCode = ZXZ_PHONE_OPEN
		record.DictType = ZXZ_PHONE_OPEN
		record.DictValue = RequestParams.Code
		record.Description = "是否开启手机注册"
		if err2 := systemDictDao.CreateOne(record).Error; err2 != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		}
	} else {
		set := map[string]interface{}{"dict_value": RequestParams.Code}
		if err2 := systemDictDao.UpdateOne(res.Id, set).Error; err2 != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		}
	}
	ctx.JSON(utils.ResponseOK())
}

type ReadExcelCountryCode struct {
	ID       string `excel:"数据ID（必填）"`
	Operator string `excel:"运营商（选填）"`
	Code     string `excel:"号段（必填）"`
}

func (*ReadExcelCountryCode) Configure(rc *exl.ReadConfig) {}

type WriteExcelCountryCode struct {
	ID       string `excel:"数据ID（必填）"`
	Operator string `excel:"运营商（选填）"`
	Code     string `excel:"号段（必填）"`
}

func (m *WriteExcelCountryCode) Configure(wc *exl.WriteConfig) {}

func CountryCodeNumberImportsHandler(ctx iris.Context) {
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ReadExcelCountryCode](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
		var dictServe services.SystemDictService
		//var dictDao admindao.Common[dao.SystemDict]
		//dictDao.DeleteByStringColumn("dict_type", ZXZ_PHONE_CODE)
		for i, model := range models {
			//从第二行开始读取
			if i == 0 || utils.StringIsEmpty(model.Code) {
				continue
			}
			dictServe.DictTypeInsertOrUpdateNumberV2(ZXZ_PHONE_CODE, model.Code, model.Operator, model.ID)
		}
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type CountryCodeQueryRequest struct {
	ID       string `json:"id"`
	Operator string `json:"operator"`
	Code     string `json:"code"`
}

func CountryCodeHandler(ctx iris.Context) {
	var RequestParams CountryCodeQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var dictServe services.SystemDictService
	if data, err := dictServe.GetValueByTypeV2(ZXZ_PHONE_CODE, RequestParams.Code, RequestParams.Operator, RequestParams.ID); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(data))
		return
	}
}

type BatchDeleteCountryCodeRequest struct {
	Ids []string `json:"ids" validate:"required"`
}

func DeleteCountryCodeHandler(ctx iris.Context) {
	var RequestParams BatchDeleteCountryCodeRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	if len(RequestParams.Ids) > 0 {
		var dictServe dao.Common[dao.SystemDict]
		if err := dictServe.RemoveUnscopedWhere(map[string]interface{}{"dict_code": RequestParams.Ids, "dict_type": ZXZ_PHONE_CODE}).Error; err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			ctx.JSON(utils.ResponseOK())
			return
		}
	} else {
		ctx.JSON(utils.ResponseServerError(errors.New("ids不能为null")))
	}
	return
}

func ExportCountryCodeRecordsHandler(ctx iris.Context) {
	var RequestParams BatchDeleteCountryCodeRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var dictServe services.SystemDictService
	data, err := dictServe.GetValueByTypeV3(ZXZ_PHONE_CODE, RequestParams.Ids)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	index := 0
	exportRecords := make([]*WriteExcelCountryCode, len(data))
	for _, model := range data {
		exportRecords[index] = &WriteExcelCountryCode{}
		exportRecords[index].ID = model.DictCode
		exportRecords[index].Code = model.DictValue
		exportRecords[index].Operator = model.Description
		index++
	}
	unix := time.Now().UnixNano()
	if err1 := exl.Write(fmt.Sprintf("./export/export_country_code_%d.xlsx", unix), exportRecords); err1 != nil {
		fmt.Println("write excel err:" + err1.Error())
		return
	}
	tempFilename := fmt.Sprintf("./export/export_country_code_%d.xlsx", unix)
	//删除本地临时文件
	defer os.Remove(tempFilename)
	bucketClient := oss.BucketClient{}
	readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/export_country_code_%d.xlsx", unix))
	bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/codeexport/export_country_code_%d.xlsx", unix))
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/codeexport/export_country_code_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
	return

}
